<template>
  <div>
    <!-- 课程列表 -->
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="所属年级">
        <el-select
          v-model="queryForm.grade"
          @change="changeGrade"
          placeholder="请选择所属科目"
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option
            v-for="(item, index) in selectArr.grade"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属学期">
        <el-select
          @change="seachData"
          v-model="queryForm.term"
          placeholder="请选择所属科目"
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option
            v-for="(item, index) in selectArr.term"
            :class="{ optionShow: setTermShow(item.label) }"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属科目">
        <el-select
          @change="seachData"
          v-model="queryForm.subject"
          placeholder="请选择所属科目"
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option
            v-for="(item, index) in selectArr.subject"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="课程名称">
        <el-input
          v-model="queryForm.name"
          placeholder="请输入课程名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="课程状态">
        <el-select
          @change="seachData"
          v-model="queryForm.status"
          placeholder="请选择课程状态"
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option label="待发布" :value="0"></el-option>
          <el-option label="已发布" :value="1"></el-option>
          <el-option label="已关闭" :value="2"></el-option>
          <!-- <el-option
            v-for="(item,index) in selectArr.status"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>-->
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="seachData()">查询</el-button>
        <el-button type="primary" @click="addUpdateCourse()"
          >新增课程</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      border
      :show-header="headerNone"
      style="width: 100%"
      header-cell-class-name="thead"
    >
      <el-table-column prop="date" label="日期" width="180">
        <template slot-scope="scope">
          <b>{{ scope.row.id }}</b>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="300">
        <template slot-scope="scope">
          <div class="u-box-hover" @click="addUpdateCourse(scope.row)">
            <div>
              <abbr :title="scope.row.name">
                <h2>{{ fontLength(scope.row.name) }}</h2>
              </abbr>
            </div>
            <div>
              <abbr :title="scope.row.description">
                <p>{{ fontLength(scope.row.description) }}</p>
              </abbr>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <b
            >{{ filterArr("grade", scope.row.grade) || "无" }}({{
              filterArr("term", scope.row.term) || "无"
            }})/{{ filterArr("subject", scope.row.subject) }}
            {{ filterArr("version", scope.row.version) }}</b
          >
          <p>
            共 {{ scope.row.period_num }} 期 每期 {{ scope.row.lesson_num }} 讲
          </p>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <div class="z-display-flex">
            <b>难度</b>
            &nbsp;
            <el-rate
              :colors="colors"
              v-model="scope.row.level"
              disabled
              void-color="red"
            ></el-rate>
          </div>

          <p>
            主讲：
            <abbr :title="scope.row.teachers">{{
              teacherSub(scope.row.teachers) || "（暂无）"
            }}</abbr>
          </p>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <b>{{ filterArr("type", scope.row.type) }}</b>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <b>学生数{{ scope.row.student_num }}人</b>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <b>发布状态</b>
          <el-switch
            v-model="scope.row.status"
            @change="switchChange($event, scope.row.id)"
          ></el-switch>
          <div>
            <a @click="setClassHour(scope.row)">设置讲次</a>
            <a @click="setCourseTerm(scope.row)">排课</a>
            <a @click="addUpdateCourse(scope.row)">编辑</a>
            <a @click="openreferenceLib(scope.row)">关联</a>
            <el-popconfirm
              title="确定要删除课程？"
              @onConfirm="deleteCourseFn(scope.row)"
            >
              <a slot="reference" v-if="!scope.row.status">删除</a>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <!-- 关联教辅书 题目 -->
    <el-dialog title="关联教辅书" :visible.sync="dialogTableVisible">
      <el-table :data="referenceLiblist">
        <el-table-column
          property="name"
          label="名称"
          width="150"
        ></el-table-column>
        <!-- <el-table-column property="status" label="状态" width="200"></el-table-column> -->
        <el-table-column
          property="update_time"
          label="更新时间"
        ></el-table-column>
        <el-table-column property label="操作">
          <template slot-scope="scope">
            <el-button @click="choosereference(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import { queyEnumByTableName, tableUpdate, tableDeleted } from "@/api/api.js";
import {
  getCourseList,
  courseDelete,
  coursePublishOn,
  closeCourse,
  referenceLibsearch,
  associateVolumeWithCourse
} from "@/api/course.js";

export default {
  name: "class-list",
  data() {
    return {
      colors: ["#99A9BF", "#F7BA2A", "red"],
      selectArr: {
        type: [],
        grade: [],
        subject: [],
        version: [],
        status: [],
        term: []
      },
      headerNone: false,
      pageIndex: 1,
      pageIndexCopy: 1,
      value: 2,
      value2: 3,
      pageSize: 10,
      totalPage: 0,
      queryForm: {
        grade: "",
        subject: "",
        name: "",
        status: "",
        term: ""
      },
      tableData: [],
      gradeLabel: "全部",

      referenceLiblist: [], // 教辅书
      dialogTableVisible: false, //
      course_id: ""
    };
  },
  activated() {
    this.getSelectData();
    this.getTableData();
  },
  methods: {
    async openreferenceLib(e) {
      let params = {
        subject: e.subject,
        textbook_version: e.version,
        volume: e.term,
        currPage: 1,
        pageSize: 50
        // status: this.search.status
      };
      let res = await referenceLibsearch(params);
      this.referenceLiblist = res[1].data.list;
      this.course_id = e.id;
      this.dialogTableVisible = true;
      console.log();
    },
    async choosereference(e) {
      const { node_id, subject } = e;
      let params = {
        node_id,
        subject,
        course_id: this.course_id,
        school_id: "11"
      };
      let res = await associateVolumeWithCourse(params);
      if (res[1].code == 0) {
        this.dialogTableVisible = false;
        this.$message({
          message: "关联成功",
          type: "success"
        });
      }
    },
    teacherSub(e) {
      if (e && e.length >= 9) {
        return e.substr(0, 8) + "...";
      } else {
        return e;
      }
    },
    seachData() {
      this.pageIndex = 1;
      this.getTableData();
    },
    setPageIndex() {
      this.pageIndexCopy = 1;
    },
    changeGrade(e) {
      this.queryForm.term = null;
      if (e === null) {
        this.gradeLabel = "全部";
      } else {
        this.selectArr.grade.map(item => {
          if (item.value === e) {
            this.gradeLabel = item.label;
          }
        });
      }
      this.seachData();
    },
    setTermShow(e) {
      if (this.gradeLabel === "全部") {
        return false;
      }
      let text = this.gradeLabel.substr(0, 1);
      let eText = e.substr(0, 1);
      let newText = "升" + text;
      // console.log(text, eText, newText)
      if (text === eText && e.indexOf("升") === -1) {
        return false;
      } else if (e.indexOf(newText) !== -1) {
        return false;
      } else if (text === "七" && e === "小升初") {
        return false;
      } else {
        return true;
      }
      //
    },
    // 删除课程
    async deleteCourseFn(e) {
      if (e.status === true) {
        this.$message({
          message: "无法删除正在发布中的课程",
          type: "warning"
        });
        return;
      }
      let res = await courseDelete({
        "vo.course_id": e.id
      });
      if (res[0]) {
        return;
      }
      this.$message({
        message: "删除课程成功",
        type: "success"
      });
      this.getTableData();
      console.log(e);
    },
    // 修改发布状态
    async switchChange(e, id) {
      let status;
      e ? (status = 1) : (status = 2);
      if (e) {
        let res = await coursePublishOn([
          {
            table_name: "nice_course",
            update: [
              {
                status: status // --  0 保存 1 保存并发布
              }
            ],
            where: [
              {
                id: id
              }
            ]
          }
        ]);
        // if (res[0]) {
        //   return
        // }
        this.getTableData();
      } else {
        let res = await closeCourse([
          {
            table_name: "nice_course",
            update: [
              {
                status: status // --  0 保存 1 保存并发布
              }
            ],
            where: [
              {
                id: id
              }
            ]
          }
        ]);
        // if (res[0]) {
        //   return
        // }
        this.getTableData();
      }

      // e
      //   ? this.$message({
      //     message: '课程发布成功',
      //     type: 'success'
      //   })
      //   : this.$message({
      //     message: '课程发布状态已关闭',
      //     type: 'warning'
      //   })
    },
    // 下拉菜单过滤
    filterArr(field, val) {
      let arr = this.selectArr[field];
      let label;
      arr.map(item => {
        if (parseInt(val) === parseInt(item.value)) {
          label = item.label;
        }
        if (item.children && item.children.length > 0) {
          item.children.map(item2 => {
            if (parseInt(val) === parseInt(item2.value)) {
              label = item.label;
            }
          });
        }
      });
      return label;
    },
    // 获取下拉菜单数据
    async getSelectData() {
      let res = await queyEnumByTableName({ tableName: "nice_course" });
      if (res[0]) {
        return;
      }
      let arr = res[1].data;
      Object.keys(this.selectArr).forEach(item => {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].fieldName === item) {
            this.selectArr[item] = arr[i].child;
          }
        }
      });
      this.selectArr = JSON.parse(
        JSON.stringify(this.selectArr)
          .split("display_value")
          .join("label")
          .split("child")
          .join("children")
          .split("t_id")
          .join("value")
      );
    },
    // 获取表数据
    async getTableData() {
      //   let res = await queryPageList({
      //     table_name: 'nice_course',
      //     currPage: this.pageIndex,
      //     pageSize: this.pageSize
      //     // property_id: 1
      //   })

      let res = await getCourseList({
        "page.currPage": this.pageIndex,
        "page.pageSize": this.pageSize,
        "nice_course.grade": this.queryForm.grade,
        "nice_course.subject": this.queryForm.subject,
        "nice_course.name": this.queryForm.name,
        "nice_course.status": this.queryForm.status,
        "nice_course.term": this.queryForm.term
      });
      if (res[0]) {
        return;
      }
      this.totalPage = res[1].data.pageList.totalCount;
      this.tableData = res[1].data.pageList.list;
      this.tableData.map(item => {
        item.status === 1 ? (item.status = true) : (item.status = false);
      });
    },
    // 老师名字过滤器
    teacherNameArr(e, type) {
      if (type === "all") {
        return e.join("、");
      } else {
        if (e && e.length < 2) {
          if (e[0].length > 6) {
            return e[0].substr(0, 6) + "...";
          } else {
            return e[0];
          }
        } else {
          let name = e[0] + "、" + e[1];
          if (name.length > 6) {
            return name.substr(0, 6) + "...";
          } else {
            return name;
          }
        }
      }
    },
    // 字数过滤器
    fontLength(e) {
      if (e && e.length > 20) {
        return e.substr(0, 20) + "...";
      } else {
        return e;
      }
    },
    // 课期
    setCourseTerm(e) {
      this.$router.push({
        name: "course-term",
        query: {
          id: e.id,
          period_num: e.period_num,
          lesson_num: e.lesson_num,
          name: e.name
        }
      });
    }, // 课时
    setClassHour(e) {
      this.$router.push({
        name: "class-hour",
        query: { id: e.id, name: e.name, status: e.status }
      });
    },
    addUpdateCourse(e) {
      if (e) {
        if (e.status === true) {
          this.$message({
            message: "当前课程为发布状态，编辑请预先关闭课程",
            type: "warning"
          });
        } else {
          this.$router.push({ name: "add-update-class", query: { id: e.id } });
        }
      } else {
        this.$router.push({ name: "add-update-class" });
      }
    },
    onSubmit() {},
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getTableData();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getTableData();
    }
  }
};
</script>
<style scoped>
abbr {
  text-decoration: none;
}
.z-display-flex {
  display: flex;
}
a {
  cursor: pointer;
}
.cascader {
}
.u-box-hover {
  cursor: pointer;
}
.u-box-hover h2 {
  display: inline;
}
.u-box-hover p {
  display: inline;
}
.optionShow {
  display: none;
}
</style>
